import { postRequest } from "request";
import { util, BaseErr } from "utils";
import { getCookieFromHeader, formatterData } from "./subTool";
import { JSESSIONIDKey } from "../../const";
async function requestNewCookie(): Promise<[err?: BaseErr, data?: any]> {
    const url =
        "http://wlw.68.gd.cn/kyhl-weixin-1.0/card/login.do?responseFunction=findByiccidMarkCallback&iccidMark=898604D21922C2711703&rfm" +
        Math.random();
    let [err, data] = await postRequest(url, { rawValue: true })(
        {},
        {
            headers: {
                DNT: "1",
                Pragma: "no-cache",
            },
            // enableProxy: true,
            // rejectUnauthorized: false,
            // proxy: "http://127.0.0.1:8899",
        }
    );
    if (!util.nilValue(err)) {
        return [err, undefined];
    }
    // 判断 结果
    let { data: resultData, headers } = data || {};
    if (resultData && resultData["app_result_key"] === "0") {
        // 数据正确
        let resultCookie = getCookieFromHeader(headers);
        if (!util.nilValue(resultCookie) && resultCookie) {
            return [undefined, resultCookie];
        }
        return [new BaseErr(-5002, "获取新cookie接口header中set-cookie没有cookie...")];
    }
    // 错误了
    let errorMsg = "获取新token失败";
    if (resultData && resultData["system_result_message_key"]) {
        errorMsg = resultData["system_result_message_key"];
    }
    return [new BaseErr(-5001, errorMsg), undefined];
}

// 获取卡片信息
async function requestCardInfo(cookie: string): Promise<[err?: BaseErr, data?: any]> {
    const url =
        "http://wlw.68.gd.cn/kyhl-weixin-1.0/card/findCardInfo.do?iccidOrPhone=&responseFunction=findCardInfoCallback&rfm=" +
        Math.random();
    let [err, data] = await postRequest(url)(
        {},
        {
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                Pragma: "no-cache",
                Cookie: `${JSESSIONIDKey}=${cookie || ""}`,
            },
            // enableProxy: true,
            // rejectUnauthorized: false,
            // proxy: "http://127.0.0.1:8899",
        }
    );

    if (!util.nilValue(err)) {
        return [err, undefined];
    }
    // 判断结果
    if (data && data["app_result_key"] === "0") {
        // 有结果了
        return [undefined, formatterData(data)];
    } else {
        // 不太对
        let errorMsg = "获取流量卡数据失败...";
        if (data && data["system_result_message_key"]) {
            errorMsg = data["system_result_message_key"];
        }
        return [new BaseErr(-5101, errorMsg), undefined];
    }
}

export { requestNewCookie, requestCardInfo };
